package com.ruoyi.applet.service.impl;

import com.ruoyi.applet.domain.AppletExam;
import com.ruoyi.applet.domain.AppletExamTopic;
import com.ruoyi.applet.domain.AppletExamUser;
import com.ruoyi.applet.domain.WechatUser;
import com.ruoyi.applet.mapper.AppletExamMapper;
import com.ruoyi.applet.mapper.AppletExamTopicMapper;
import com.ruoyi.applet.mapper.AppletExamUserMapper;
import com.ruoyi.applet.mapper.WechatUserMapper;
import com.ruoyi.applet.service.IAppletExamUserService;
import com.brisk.common.core.domain.AjaxResult;
import com.brisk.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * examUserService业务层处理
 *
 * @author PengFei Deng
 * @date 2022-04-14
 */
@Service
public class AppletExamUserServiceImpl implements IAppletExamUserService {
    @Autowired
    private AppletExamUserMapper appletExamUserMapper;

    @Autowired
    private AppletExamMapper appletExamMapper;


    @Autowired
    private WechatUserMapper wechatUserMapper;

    @Autowired
    private AppletExamTopicMapper appletExamTopicMapper;

    /**
     * 查询examUser
     *
     * @param joinId examUser主键
     * @return examUser
     */
    @Override
    public AppletExamUser selectAppletExamUserByJoinId(Long joinId) {
        return appletExamUserMapper.selectAppletExamUserByJoinId(joinId);
    }

    /**
     * 查询examUser列表
     *
     * @param appletExamUser examUser
     * @return examUser
     */
    @Override
    public List<AppletExamUser> selectAppletExamUserList(AppletExamUser appletExamUser) {
        return appletExamUserMapper.selectAppletExamUserList(appletExamUser);
    }

    /**
     * 新增examUser
     *
     * @param appletExamUser examUser
     * @return 结果
     */
    @Override
    public int insertAppletExamUser(AppletExamUser appletExamUser) {
        return appletExamUserMapper.insertAppletExamUser(appletExamUser);
    }

    /**
     * 修改examUser
     *
     * @param appletExamUser examUser
     * @return 结果
     */
    @Override
    public int updateAppletExamUser(AppletExamUser appletExamUser) {
        return appletExamUserMapper.updateAppletExamUser(appletExamUser);
    }

    /**
     * 批量删除examUser
     *
     * @param joinIds 需要删除的examUser主键
     * @return 结果
     */
    @Override
    public int deleteAppletExamUserByJoinIds(Long[] joinIds) {
        return appletExamUserMapper.deleteAppletExamUserByJoinIds(joinIds);
    }

    /**
     * 删除examUser信息
     *
     * @param joinId examUser主键
     * @return 结果
     */
    @Override
    public int deleteAppletExamUserByJoinId(Long joinId) {
        return appletExamUserMapper.deleteAppletExamUserByJoinId(joinId);
    }

    @Override
    public AppletExamUser selectAppletExamUserByPhone(String userPhone) {
        return appletExamUserMapper.selectAppletExamUserByPhone(userPhone);
    }

    @Override
    public AjaxResult addRecord(AppletExamUser appletExamUser) {
        AppletExam appletExam = appletExamMapper.selectAppletExamByExamId(Math.toIntExact(appletExamUser.getExamId()));
        if (ObjectUtils.isEmpty(appletExam)) return AjaxResult.error("获取试题信息失败！");

        //查询是否有答题记录
        AppletExamUser selectUser = new AppletExamUser();
        selectUser.setUserId(appletExamUser.getUserId());
        selectUser.setExamId(appletExam.getExamId());
        List<AppletExamUser> appletExamUsers = appletExamUserMapper.selectAppletExamUserList(selectUser);
        if (appletExamUsers.size() > 0) return AjaxResult.error("您已参加此次答题！");

        //判断用户是否缺失答案
        String[] userAnswers = appletExamUser.getUserAnswer().split("-"); // 此次答题的数量 答案用 - 拼接
        if (userAnswers.length <= 0) return AjaxResult.error("用户答案缺失！");
        //查询试题的答案
        List<AppletExamTopic> topics = appletExamTopicMapper.appletGetByExamIdWithAnswer(Math.toIntExact(appletExamUser.getExamId()));
        if (userAnswers.length != topics.size()) return AjaxResult.error("您未答完所有试题！");
        //获取用户答题正确题目
        Integer trueSum = getTrueSum(userAnswers, topics);
        appletExamUser.setJoinTime(DateUtils.getNowDate());
        appletExamUser.setUserTrueSum(String.valueOf(trueSum));
        appletExamUser.setExamName(appletExam.getExamName());
        //计算用户的答题正确率
        if (trueSum == null || trueSum == 0) {
            appletExamUser.setUserAccuracy(new BigDecimal("0.00"));
        } else {
            BigDecimal acc = new BigDecimal(trueSum).divide(new BigDecimal(userAnswers.length), 2, RoundingMode.FLOOR);
            appletExamUser.setUserAccuracy(acc);
        }
        int res = appletExamUserMapper.insertAppletExamUser(appletExamUser);
        //更新答题参与人数
        appletExam.setPeopleSum(appletExam.getPeopleSum() + 1);
        appletExamMapper.updateAppletExam(appletExam);
        //更新用户里程数 答对一个奖励 +10 里程
        if (trueSum > 0) {
            int temp = trueSum * 10;
            WechatUser wechatUser = new WechatUser();
            wechatUser.setUserId(appletExamUser.getUserId());
            wechatUser.setMileage(new BigDecimal(temp));
            wechatUserMapper.updateUserNumberByUserId(wechatUser);
        }


        String msg = "参与成功！本次一共 " + topics.size() + " 道题目，您答对了 " + trueSum + " 道题目，正确率：" + (appletExamUser.getUserAccuracy().multiply(new BigDecimal(100))) + "%";
        return res > 0 ? AjaxResult.success(msg) : AjaxResult.error("参与失败！");
    }


    /**
     * 获取用户答题正确的数量
     *
     * @param userAnswers 用户答案
     * @param topics      保存答案
     * @return java.lang.Integer
     * @author PengFei Deng
     * @date 2022/4/22 23:26
     */
    public Integer getTrueSum(String[] userAnswers, List<AppletExamTopic> topics) {
        int trueSum = 0; //正确的题目
        for (int i = 0; i < topics.size(); i++) {
            AppletExamTopic appletExamTopic = topics.get(i);
            //多选题目
            if ("2".equalsIgnoreCase(appletExamTopic.getTopicType())) {
                //正确答案 分割成数组  用户答案分割成数组  循环 用户答案 匹配
                String[] userTemp = userAnswers[i].split("");
                String[] trueTemp = appletExamTopic.getTrueAnser().split("-");
                //如果两个数组不相等  那个答案一定是错误的  这里不考虑 半对情况
                if (userTemp.length != trueTemp.length) {
                    continue;
                }
                boolean flag = false; // 是否正确的标志
                for (String value : userTemp) {
                    int sumTemp = 0; //计数
                    for (String s : trueTemp) {
                        if (s.equalsIgnoreCase(value)) {
                            sumTemp++;
                            break;
                        }
                    }
                    // 循环完了 如果没有就代表 用户的答案包含了错误的答案
                    if (sumTemp == 0) {
                        flag = false;
                        break;
                    }
                    flag = true;
                }
                if (flag) trueSum++;
            } else {
                //判断题和单选题
                if (appletExamTopic.getTrueAnser().equalsIgnoreCase(userAnswers[i]))
                    trueSum++;
            }

        }
        return trueSum;
    }


}
